// enigma.js
// 2009-01-24

/*
The MIT License - http://www.opensource.org/licenses/mit-license.php

Copyright (c) 2009 Tor Edvardsson

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

var Enigma = function () {
  
  var Queue = function (delay) {
    this._init();
  };
  
  Queue.prototype = {
  
    _init: function (delay) {
      this.delay = typeof delay !== "undefined"  && delay > 0 ? delay : 0;
      this.q = [];
      this.id = null;
      this.handle = 1;
    },
    
    add: function (fn, args) {
      if (typeof fn === "function") {
        this.q.push({fn: fn, args: args, handle: this.handle});
        return this.handle++;
      }
      return false;
    },
    
    run: function () {
      var that = this;
      if (!that.id) {
        var o = that.q[0];
        if (o) {
          that.id = setTimeout(function () {
            that.q.shift();
            o.fn.apply(o.fn, o.args); // wrong scope?
            if (that.id) {
              that.id = null;
              that.run();
            }
          }, this.delay);
          return true;
        }
      }
      return false;
    },
    
    pause: function () {
      clearTimeout(this.id);
      this.id = null;
    },
    
    stop: function () {
      this.pause();
      this.q = [];
    },
    
    remove: function (handle) {
      for (var i = 0; i < this.q.length; i++) {
        if (handle === this.q[i].handle) {
          this.q.splice(i, 1);
        }
      }
    }
  };
  
  var requestQueue = new Queue(100);
  var enigmaQueue = new Queue();
  
   var Event = function () {
    var e = {};
    
    function subscribe(name, fn) {
      if (typeof fn === "function") {
        e[name] = fn;
        return true;
      }
      return false;
    }
    
    function notify(name, args) {
      if (e[name]) {
        return e[name](args);
      }
      return false;
    }
  
    return {
      subscribe: subscribe,
      notify: notify
    };
  }();
  
  var Server = function () {
  
    function request(req) {
      var parts = req._url.split("?", 2);
      var form = {};
      if (parts && parts[0] && parts[1]) {
        var forms = parts[1].split("&");
        for (var i = 0; i < forms.length; i++) {
          var tmp = forms[i].split("=", 2);
          form[tmp[0]] = tmp[1];
        }
      }
      
      var action = parts[0];
      enigmaQueue.add(function () {
        if (action) {
          var ret = Event.notify(action, form);
          req.responseText = ret;
        }
        req.readyState = 4;
        req.status = 200;
        if (typeof req.onreadystatechange === "function") {
          req.onreadystatechange();
        }
      });
      enigmaQueue.run();
    }
    
     return {
      request: request
    };
  }();

  var XMLHttpRequest = function () {
    this._init();
  };
  
  XMLHttpRequest._enigma = true;
  
  XMLHttpRequest.prototype = {
    
    _init: function () {
      this.readyState = 0;
      this.responseText = null;
      this.responseXML = null;
      this._send_flag = false;
      this._error_flag = false;
      this._headers = {};
      this._insecure_headers = {"accept-charset": true, "accept-encoding": true,
                                "connection": true, "content-length": true,
                                "content-transfer-encoding": true,
                                "date": true, "expect": true, "host": true,
                                "keep-alive": true, "referer": true, "te": true,
                                "trailer": true, "transfer-encoding": true,
                                "upgrade": true, "vida": true};
    },
  
    // TODO 1+
    abort: function () {
      requestQueue.remove(this._handle);
      this._error_flag = true;
      this._headers = {};
      this.readyState = 0;
    },
    
    // TODO 1 - 11, 13 - 21
    open: function (method, url, async, user, password) {
      this._method = "GET";      
      this._url = url;
      this._async = typeof async !== "undefined" ? async : true;
      this._user = typeof user !== "undefined" ? user: "";
      this._password = typeof password !== "undefined" ? password: "";
      this.readyState = 1;
      this._send_flag = false;
    },
    
    // TODO 4+
    send: function (data) {
      if (this.readyState !== 1 || this._send_flag) {
        throw new Error("INVALID_STATE_ERR");
      }
      if (this._async) {
        this._send_flag = true;
      }
      if (this.method === "GET") {
        data = null;
      }
      this._handle = requestQueue.add(Server.request, [this]);
      requestQueue.run();
      this.readyState = 2;
    },
    
    // TODO 3, 5
    setRequestHeader: function (header, value) {
      if (this.readyState !== 1 || this._send_flag) {
        throw new Error("INVALID_STATE_ERR");
      } else {
        if (value === null) {
          return;
        } else {
          var s = header.toLowerCase();
          if (this._insecure_headers[s] || 
              s.indexOf("proxy-") === 0  ||
              s.indexOf("sec-") === 0) {
            return;
          }
          if (!this._headers[header]) {
            this._headers[header] = [value];
            return;
          } else {
            this._headers[header].push(value);
            return;
          } 
        }
      }
    },
    
    // TODO 3 and 2, 4, 5
    getAllResponseHeaders: function (header) {
      if (this.readyState === 0 ||
          this.readyState === 1) {
          throw new Error("INVALID_STATE_ERR");
      }
      var args = Array.prototype.slice.call(arguments);
      if (!args.length) {
        if (this._error_flag) {
          return "";
        }
        return; // TODO return headers
      } else {
        if (this._error_flag) {
          return null;
        }
        return null; // TODO return header
      }
    }
  };
  
  return {
    XMLHttpRequest: XMLHttpRequest,
    subscribe: Event.subscribe,
    Queue: new Queue()
  };
}();
